<?php


namespace App\Models\CacheModel;

use app\common\lib\astrolog\Astrolog;
use app\common\lib\Util;
use App\Models\Api\BaseCache;
use app\everyday\controller\Index as FortuneIndex;
use app\common\lib\exception\ApiException;
use think\Env;
use AstroTool\Cache\CacheManage;

class FortuneCache extends BaseCache
{
    /**
     * 缓存开关
     * @var int
     */
    public $cache_on = 1;

    /**
     * @var array 幸运色
     */
    protected $colors;

    /**
     * @var array 幸运方位
     */
    protected $directions;

    /**
     * @var array 幸运数字
     */
    protected $numbers;

    /**
     * @var array 幸运星座
     */
    protected $constellations;

    /**
     * @var array 运势指南类型icon_urls
     */
    protected $guide_icon_urls;

    /**
     * 星象变动 名字
     * @var string
     */
    protected $astroName = '星象变动';

    /**
     * 星象变动 图标
     * @var  string
     */
    protected $astroIconUrl;

    /**
     * 困难、警戒、平平、吉利、大吉 name和color
     * @var array
     */
    protected $luckAdversity = [
        0 => ['name' => '困难', 'color' => '#7775ff',],
        1 => ['name' => '警戒', 'color' => '#ffa536',],
        2 => ['name' => '平平', 'color' => '#ffed17',],
        3 => ['name' => '吉利', 'color' => '#00f4e7',],
        4 => ['name' => '大吉', 'color' => '#00e9a0',],
    ];

    /**
     * 日运永久免费解锁范围 2018-12-25到2019-12-31
     * @var array
     */
    protected static $fortune_unlock_time = [
        1545667200,
        1546272000,
    ];

    public function initialize()
    {
        parent::initialize();
        $this->cache_on = config('cache.switch');
        $fortune_config = config('fortune');
        //幸运色
        $this->colors['gold_one'] = $fortune_config['gold_one'];
        $this->colors['gold_two'] = $fortune_config['gold_two'];
        $this->colors['gold_three'] = $fortune_config['gold_three'];
        $this->colors['wood_one'] = $fortune_config['wood_one'];
        $this->colors['wood_three'] = $fortune_config['wood_three'];
        $this->colors['water_one'] = $fortune_config['water_one'];
        $this->colors['water_two'] = $fortune_config['water_two'];
        $this->colors['water_three'] = $fortune_config['water_three'];
        $this->colors['fire_one'] = $fortune_config['fire_one'];
        $this->colors['fire_two'] = $fortune_config['fire_two'];
        $this->colors['fire_three'] = $fortune_config['fire_three'];
        $this->colors['soil_one'] = $fortune_config['soil_one'];
        $this->colors['soil_two'] = $fortune_config['soil_two'];
        $this->colors['soil_three'] = $fortune_config['soil_three'];


        //幸运方位
        $this->directions['east'] = $fortune_config['east'];
        $this->directions['south'] = $fortune_config['south'];
        $this->directions['west'] = $fortune_config['west'];
        $this->directions['north'] = $fortune_config['north'];
        $this->directions['southeast'] = $fortune_config['southeast'];
        $this->directions['northeast'] = $fortune_config['northeast'];
        $this->directions['southwest'] = $fortune_config['southwest'];
        $this->directions['northwest'] = $fortune_config['northwest'];

        //幸运数字
        $this->numbers['one'] = $fortune_config['one'];
        $this->numbers['two'] = $fortune_config['two'];
        $this->numbers['three'] = $fortune_config['three'];
        $this->numbers['four'] = $fortune_config['four'];
        $this->numbers['five'] = $fortune_config['five'];
        $this->numbers['six'] = $fortune_config['six'];
        $this->numbers['seven'] = $fortune_config['seven'];
        $this->numbers['eight'] = $fortune_config['eight'];
        $this->numbers['nine'] = $fortune_config['nine'];

        //幸运星座
        $this->constellations['aries'] = $fortune_config['aries'];
        $this->constellations['taurus'] = $fortune_config['taurus'];
        $this->constellations['gemini'] = $fortune_config['gemini'];
        $this->constellations['cancer'] = $fortune_config['cancer'];
        $this->constellations['leo'] = $fortune_config['leo'];
        $this->constellations['virgo'] = $fortune_config['virgo'];
        $this->constellations['libra'] = $fortune_config['libra'];
        $this->constellations['scorpio'] = $fortune_config['scorpio'];
        $this->constellations['sagittarius'] = $fortune_config['sagittarius'];
        $this->constellations['capricornus'] = $fortune_config['capricornus'];
        $this->constellations['aquarius'] = $fortune_config['aquarius'];
        $this->constellations['pisces'] = $fortune_config['pisces'];

        //运势指南icon_urls
        $this->guide_icon_urls['treasure'] = $fortune_config['treasure'];
        $this->guide_icon_urls['job'] = $fortune_config['job'];
        $this->guide_icon_urls['health'] = $fortune_config['health'];
        $this->guide_icon_urls['school'] = $fortune_config['school'];
        $this->guide_icon_urls['love'] = $fortune_config['love'];
        $this->guide_icon_urls['contact'] = $fortune_config['contact'];
        $this->guide_icon_urls['trip'] = $fortune_config['trip'];
        $this->guide_icon_urls['family'] = $fortune_config['family'];
        $this->guide_icon_urls['mood'] = $fortune_config['mood'];

        // 星象变动 图标
        $this->astroIconUrl = config('fortune.astro');
    }

    /**
     * 获取首页 运势及天象
     * @param $map
     * @return array|bool|mixed|string
     * @throws ApiException
     * @throws \Exception
     */
    public function getHomePageFortune($map)
    {
        $time_now = $map['time'];
        $recodeInfo = $map['recode'];
        $dailyTime = strtotime(date('Y-m-d', $time_now) . ' 12:00:00');

        if ($this->cache_on == 1)
        {
            $fortuneData = CacheManage::getInstance()->setCacheConfig('fortune.fortune_home', $recodeInfo['id'] . ':' . $dailyTime)->getCache();
            if (!$fortuneData)
            {
                $data = $this->calculateHomeFortune($dailyTime, $recodeInfo);
                $fortuneData = $data;

                $data['revive_day'] = $this->transReviveDayFromOriginalToCache($data['revive_day']);
                $data = array_map(function ($val)
                {
                    return json_encode($val);
                }, $data);

                CacheManage::getInstance()->setCacheConfig('fortune.fortune_home', $recodeInfo['id'] . ':' . $dailyTime)->setCache($data, 'details', false);
            } else
            {
                $fortuneData = array_map(function ($val)
                {
                    return json_decode($val, true);
                }, $fortuneData);

                $fortuneData['revive_day'] = $this->transReviveDayFromCacheToOriginal($fortuneData['revive_day']);
            }
        } else
        {
            $fortuneData = $this->calculateHomeFortune($dailyTime, $recodeInfo);
        }

        return $fortuneData;
    }

    /**
     * 删除日运缓存
     * @param $rid
     * @param $time
     * @throws \Exception
     */
    public static function rmFortuneDayCache($rid, $time)
    {
//        CacheManage::getInstance()->setCacheConfig('fortune.fortune_home', $rid . ':*')->rmCache();
//        // 批量删除所有该档案的日运缓存
//        CacheManage::getInstance()->setCacheConfig('fortune.fortune_day', $rid . ':*')->batchDelKey();
        // 仅删除北京时间当天的缓存
        CacheManage::getInstance()->setCacheConfig('fortune.fortune_home', $rid . ':' . $time)->rmCache();
        // 批量删除所有该档案的日运缓存
        CacheManage::getInstance()->setCacheConfig('fortune.fortune_day', $rid . ':' . $time)->batchDelKey();
    }

    /**
     * 计算首页 运势 天象等
     * @param $dailyTime
     * @param $recode_info
     * @return mixed
     * @throws ApiException
     */
    public function calculateHomeFortune($dailyTime, $recode_info)
    {
        $dailyFortune = new FortuneIndex();
        $timeinfo = [
            'year' => date('Y', $dailyTime),
            'month' => date('m', $dailyTime),
            'day' => date('d', $dailyTime),
            'hour' => date('H', $dailyTime),
            'minute' => date('i', $dailyTime),
        ];
        $timeinfo['timezone'] = 8;
        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'], $timeinfo['minute'], 0,
            $timeinfo['month'], $timeinfo['day'], $timeinfo['year']) ? 1 : 0;

        if ($recode_info['month'] * 1 == $timeinfo['month'] * 1 && $recode_info['day'] * 1 == $timeinfo['day'] * 1) $dailyFortune->isBirth = true;

        $dailyFortune->astro = Astrolog::getInstance();
        $dailyFortune->astro
            ->setRecode1($recode_info)
            ->setAdvance($timeinfo)
            ->setExecPrefix(config('astrolog.prefix'))
            ->setIsAstrolabe(false)
            ->setUserSetting(config('astroset.setting1'))
            ->setGetDatas(['now', 'natal', 'transits', 'thirdprogressed'])
            ->getAstroDatas();

        $dailyFortune->nowData = $dailyFortune->astro->getDatas('now');
        $dailyFortune->natalData = $dailyFortune->astro->getDatas('natal');
        $dailyFortune->transitsData = $dailyFortune->astro->getDatas('transits');
        $dailyFortune->thirdprogressedData = $dailyFortune->astro->getDatas('thirdprogressed');
        $dailyFortune->active = $dailyFortune->getActive();
        $lucky_name = $dailyFortune->getSuitable($recode_info, $dailyTime, true);
        $forbid_name = $dailyFortune->getAvoid(true);
        $avoid = [];
        // 宜中出现过的，忌中不显示
        if (!empty($forbid_name)) foreach ($forbid_name as $avd) if (!in_array($avd, $lucky_name)) $avoid[] = $avd;
        if (empty($avoid)) $avoid[] = '百无禁忌';

        $revive_day = $dailyFortune->getTopic($recode_info, $dailyTime, true);

        $sun_in_sign = $dailyFortune->natalData['planets'][0]['in_sign_id'] ?? 1;// 如失败 则为白羊座
        // 获取今日天象
        $timeinfo['hour'] = 0;

        $dailyFortune->nowData = $dailyFortune->astro
            ->setAdvance($timeinfo)
            ->setGetDatas(['now'])
            ->getAstroDatas()
            ->getDatas('now');

        $tips = $dailyFortune->getNow();

        //赋值
        $data['lucky_name'] = $lucky_name;
        $data['forbid_name'] = $avoid;
        $data['revive_day'] = $revive_day;
        $data['sun_in_sign'] = $sun_in_sign;
        $data['tips'] = $tips;

        return $data;
    }

    /**
     * 获取首页 运势及天象
     * @param $map
     * @return array
     * @throws ApiException
     * @throws \Exception
     */
    public function getHomePageFortune1($map): array
    {
        $rid = (int)$map['recode']['id'];

        $fortuneInfo = $this->getDayFortune(['rid' => $rid, 'time' => $map['time'], 'uid' => $map['uid']]);

        $fortuneData = $this->praySort($fortuneInfo['fortune_list']);

        return [
            'sun_in_sign' => $fortuneInfo['sun_in_sign'],
            'tips' => $fortuneInfo['tips'],
            'pray_index' => $fortuneData['pray_index'],
            'revive_day' => current($fortuneInfo['revive_day']),
            'luck_adversity' => $fortuneInfo['luck_adversity'],
            'fortune_list' => $fortuneData['fortune_list'],
        ];
    }

    /**
     * 获取许愿顺序
     * @param array $fortuneList
     * @return array
     */
    public function praySort(array $fortuneList = []): array
    {
        $colors = [
            // 0 => ['name' => '困难','color' => '#7775ff',],
            // 1 => ['name' => '警戒', 'color' => '#ffa536',],
            // 2 => ['name' => '平平', 'color' => '#ffed17',],
            // 3 => ['name' => '吉利', 'color' => '#00f4e7',],
            // 4 => ['name' => '大吉', 'color' => '#00e9a0',],
            '#7775ff' => 1,
            '#ffa536' => 2,
            '#ffed17' => 3,
            '#00f4e7' => 4,
            '#00e9a0' => 5,
        ];
        $prayGoods = config('zhunleorder.pray_goods');

        $goods = [];
        foreach ($prayGoods as $value)
        {
            $goods[$value['name']] = $value;
        }
        $ossHost = Env::get('host.photo');
        $sort = [];
        foreach ($fortuneList as $index => $fortuneItem)
        {
            if ($fortuneItem['color'] !== '#00e9a0' || $fortuneItem['score'] < 100)
            { // 如果当前运势不是大吉 并且 运势小于100
                $key = 100 * ($colors[$fortuneItem['color']] ?? 1) + $fortuneItem['score'];
                $sort[$key] = $index;
            }
            $fortuneList[$index]['toast_name'] = $goods[$fortuneItem['name']]['title'] ?? '';
            $fortuneList[$index]['toast_num'] = $goods[$fortuneItem['name']]['coin_num'] ?? 10;
            $fortuneList[$index]['toast_bg'] = $ossHost . ($goods[$fortuneItem['name']]['icon'] ?? '');
            $fortuneList[$index]['toast_type'] = $goods[$fortuneItem['name']]['id'] ?? 0;
            $fortuneList[$index]['start_num'] = $goods[$fortuneItem['name']]['start_num'] ?? 70;
            $fortuneList[$index]['toast_price'] = $goods[$fortuneItem['name']]['now_prize'] ?? 1;
        }

        if ($sort)
        {
            ksort($sort); // 排序  有小到大
            $sort = array_values($sort); // 获取下标
        }

        return [
            'pray_index' => $sort,
            'fortune_list' => $fortuneList,
        ];
    }

    /**
     * 获取日运
     * @param $map
     * @param int $dayFortuneVersion 日运版本 1=>旧版本 2=>2.4.1厄运消除及以后版本
     * @return array|bool|mixed|string
     * @throws ApiException
     */
    public function getDayFortune($map, $dayFortuneVersion = 1)
    {
        $rid = $map['rid'];
        $uid = $map['uid'];
        $prayDate = date('Ymd', $map['time']);
        $time = strtotime(date('Y-m-d', $map['time']) . ' 12:00:00');

        if ($this->cache_on == 1)
        {
            $fortuneData = CacheManage::getInstance()->setCacheConfig('fortune.fortune_day', $rid . ':' . $time . ':' . $dayFortuneVersion)->getCache();
            if (!$fortuneData || !isset($fortuneData['sun_in_sign']))
            {
                $data = $this->calculateDayFortune($rid, $time, $dayFortuneVersion);
                $fortuneData = $data;

                $data = $this->transFromOriginalToCache($data);
                unset($data['astro_name']);
                unset($data['astro_icon_url']);
                unset($data['luck_adversity']);
                $data = array_map(function ($val)
                {
                    return json_encode($val);
                }, $data);

                CacheManage::getInstance()->setCacheConfig('fortune.fortune_day', $rid . ':' . $time . ':' . $dayFortuneVersion)->setCache($data, 'details', false);
            } else
            {
                $fortuneData = array_map(function ($val)
                {
                    return json_decode($val, true);
                }, $fortuneData);

                $fortuneData = $this->transFromCacheToOriginal($fortuneData);

                $fortuneData['astro_name'] = $this->astroName;
                $fortuneData['astro_icon_url'] = $this->astroIconUrl;
                $fortuneData['luck_adversity'] = $this->luckAdversity;
            }
        } else
        {
            $fortuneData = $this->calculateDayFortune($rid, $time, $dayFortuneVersion);
        }
        // 祈福功能关闭
//        if ($prayDate === date('Ymd'))
//        {
//            $prayInfo = (new ZhunleUserAccountRecord())->getTodayPrayInfo($uid, $rid, $prayDate);
//            if ($prayInfo)
//            {
//                $prayGoods = config('zhunleorder.pray_goods');
//                $prayedInfo = [];
//                foreach ($prayInfo as $item)
//                {   // 获取已许愿的信息
//                    $prayedInfo[] = $prayGoods[$item]['name']; // 婚恋|出行|家人|心情....
//                }
//
//                foreach ($fortuneData['fortune_list'] as $key => $value)
//                {
//                    if (in_array($value['name'], $prayedInfo, true))
//                    {
//                        $fortuneData['fortune_list'][$key]['score'] = 100;  // 满分
//                        $fortuneData['fortune_list'][$key]['color'] = '#00e9a0'; // 大吉
//                    }
//                }
//            }
//        }

        return $fortuneData;
    }

    /**
     * @param $rid
     * @param $time
     * @param int $dayFortuneVersion 日运版本 1=>旧版本 2=>2.4.1厄运消除及以后版本
     * @return array
     * @throws ApiException
     */
    public function calculateDayFortune($rid, $time, $dayFortuneVersion = 1)
    {
        $dailyFortune = new FortuneIndex();
        $dailyFortune->dayFortuneVersion = $dayFortuneVersion; //  日运版本 1=>旧版本 2=>2.4.1厄运消除及以后版本
        $fortune_cache = $dailyFortune->init($rid, $time);
        $temp[] = $fortune_cache['fortune_list'][4];
        $temp[] = $fortune_cache['fortune_list'][3];
        $temp[] = $fortune_cache['fortune_list'][1];
        $temp[] = $fortune_cache['fortune_list'][0];
        $temp[] = $fortune_cache['fortune_list'][6];
        $temp[] = $fortune_cache['fortune_list'][2];
        $temp[] = $fortune_cache['fortune_list'][5];
        $temp[] = $fortune_cache['fortune_list'][7];
        $temp[] = $fortune_cache['fortune_list'][8];
        //婚恋/学习/事业/财富/出行/健康/交际/家人/心情
        $fortune_cache['fortune_list'] = $temp;

        return $fortune_cache;
    }

    /**
     * 把原始数据 转换为 缓存的数据
     * @param $fortune_cache
     * @return mixed
     */
    private function transFromOriginalToCache($fortune_cache)
    {
        $fortuneConfigs = config('fortune');
        //幸运色
        foreach ($this->colors as $k => $v)
        {
            if ($v == $fortune_cache['lucky_symbol'][0]['icon_url'])
            {
                $fortune_cache['lucky_symbol'][0]['icon_url'] = $k;
            }
        }

        //幸运方位
        foreach ($this->directions as $k => $v)
        {
            if ($v == $fortune_cache['lucky_symbol'][1]['icon_url'])
            {
                $fortune_cache['lucky_symbol'][1]['icon_url'] = $k;
            }
        }

        //幸运数字
        foreach ($this->numbers as $k => $v)
        {
            if ($v == $fortune_cache['lucky_symbol'][2]['icon_url'])
            {
                $fortune_cache['lucky_symbol'][2]['icon_url'] = $k;
            }
        }

        //幸运星座
        foreach ($this->constellations as $k => $v)
        {
            if ($v == $fortune_cache['lucky_symbol'][3]['icon_url'])
            {
                $fortune_cache['lucky_symbol'][3]['icon_url'] = $k;
            }
        }

        //转换某某之日列表
        foreach ($fortune_cache['revive_day'] as $k => $v)
        {
            $fortune_cache['revive_day'][$k] = $this->transReviveDayFromOriginalToCache($v);
        }

        //转换 几大方面的运势指南 列表
        foreach ($fortune_cache['fortune_advice'] as $k => $v)
        {
            $fortune_cache['fortune_advice'][$k] = $this->transAdivceFromOriginalToCache($v);
        }
        $fortuneAstroTips = $fortuneConfigs['astro_tips'];
        //转换 星象变动 列表
        foreach ($fortune_cache['astro_tips'] as $k => $v)
        {
            foreach ($fortuneAstroTips as $tips_k => $tips_v)
            {
                if ($tips_v === $v)
                {
                    $fortune_cache['astro_tips'][$k] = $tips_k;
                    break;
                }
            }
        }

        //转换 女神赠言（一条）
        foreach ($fortuneConfigs['word_tips'] as $k => $v)
        {
            if ($fortune_cache['goddess_list']['tips'] == $v['tips'])
            {
                $fortune_cache['goddess_list']['tips'] = $k;
                $fortune_cache['goddess_list']['from'] = $k;
                break;
            }
        }

        return $fortune_cache;

    }

    /**
     * 把缓存数据转换为返回给app的数据
     * @param $fortune_cache
     * @return mixed
     */
    private function transFromCacheToOriginal($fortune_cache)
    {
        $fortuneConfigs = config('fortune');
        //幸运色
        $color_icon_url = $fortune_cache['lucky_symbol'][0]['icon_url'];
        if (!empty($color_icon_url) && substr($color_icon_url, strlen($color_icon_url) - 3, 3) != 'png')
        {
            $fortune_cache['lucky_symbol'][0]['icon_url'] = $this->colors[$color_icon_url];
        }

        //幸运方位
        $color_direction_url = $fortune_cache['lucky_symbol'][1]['icon_url'];
        if (!empty($color_direction_url) && substr($color_direction_url, strlen($color_direction_url) - 3, 3) != 'png')
        {
            $fortune_cache['lucky_symbol'][1]['icon_url'] = $this->directions[$color_direction_url];
        }

        //幸运数字
        $color_number_url = $fortune_cache['lucky_symbol'][2]['icon_url'];
        if (!empty($color_number_url) && substr($color_number_url, strlen($color_number_url) - 3, 3) != 'png')
        {
            $fortune_cache['lucky_symbol'][2]['icon_url'] = $this->numbers[$color_number_url];
        }

        //幸运星座
        $color_constellation_url = $fortune_cache['lucky_symbol'][3]['icon_url'];
        if (!empty($color_constellation_url) && substr($color_constellation_url, strlen($color_constellation_url) - 3, 3) != 'png')
        {
            $fortune_cache['lucky_symbol'][3]['icon_url'] = $this->constellations[$color_constellation_url];
        }

        //转换某某之日列表
        foreach ($fortune_cache['revive_day'] as $k => $v)
        {
            $fortune_cache['revive_day'][$k] = $this->transReviveDayFromCacheToOriginal($v);
        }

        //转换 几大方面的运势指南 列表
        foreach ($fortune_cache['fortune_advice'] as $k => $v)
        {
            $fortune_cache['fortune_advice'][$k] = $this->transAdivceFromCacheToOriginal($v);
        }

        //转换 星象变动 列表
        foreach ($fortune_cache['astro_tips'] as $k => $v)
        {
            if (strlen($v) < 4)
            {
                $fortune_cache['astro_tips'][$k] = $fortuneConfigs['astro_tips'][$v];
            }
        }

        //转换 女神赠言（一条）
        if (strlen($fortune_cache['goddess_list']['tips']) < 4)
        {
            $fortune_cache['goddess_list'] = $fortuneConfigs['word_tips'][$fortune_cache['goddess_list']['tips']];
        }


        return $fortune_cache;
    }

    /**
     * 某某之日的原始数据转换为缓存数据
     * @param $revive_day
     * @return mixed
     */
    private function transReviveDayFromOriginalToCache($revive_day)
    {
        $fortuneConfigs = config('fortune');
        //**之日名字
        foreach ($fortuneConfigs['day'] as $k => $day)
        {
            if ($day === $revive_day['name'])
            {
                $revive_day['name'] = $k;
                break;
            }
        }
        //**之日描述
        foreach ($fortuneConfigs['day_des'] as $k => $day)
        {
            if ($day === $revive_day['tips'])
            {
                $revive_day['tips'] = $k;
                break;
            }
        }
        //**之日图标url
        foreach ($fortuneConfigs['icon_url'] as $k => $v)
        {
            if ($v === $revive_day['icon_url'])
            {
                $revive_day['icon_url'] = $k;
                break;
            }
        }
        //**之日弹出图标url
        foreach ($fortuneConfigs['tip_url'] as $k => $v)
        {
            if ($v === $revive_day['tips_url'])
            {
                $revive_day['tips_url'] = $k;
                break;
            }
        }

        return $revive_day;
    }

    /**
     * 某某之日的缓存数据转换为原始数据
     * @param $revive_day
     * @return mixed
     */
    private function transReviveDayFromCacheToOriginal($revive_day)
    {
        $fortuneConfigs = config('fortune');
        //**之日名字
        if (strlen($revive_day['name']) < 3)
        {
            $revive_day['name'] = $fortuneConfigs['day'][$revive_day['name']];
        }
        if (strlen($revive_day['tips']) < 3)
        {
            $revive_day['tips'] = $fortuneConfigs['day_des'][$revive_day['tips']];
        }
        if (substr($revive_day['icon_url'], strlen($revive_day['icon_url']) - 3, 3) != 'png')
        {
            $revive_day['icon_url'] = $fortuneConfigs['icon_url'][$revive_day['icon_url']];
        }
        if (substr($revive_day['tips_url'], strlen($revive_day['tips_url']) - 3, 3) != 'png')
        {
            $revive_day['tips_url'] = $fortuneConfigs['tip_url'][$revive_day['tips_url']];
        }

        return $revive_day;
    }

    /**
     * 单个运势指南 从原始数据 转换为 缓存数据
     * @param $fortune_advice
     * @return array
     */
    private function transAdivceFromOriginalToCache($fortune_advice)
    {
        $fortuneConfigs = config('fortune');

        foreach ($this->guide_icon_urls as $k => $v)
        {
            if ($v == $fortune_advice['icon_url'])
            {
                //转换icon_url
                $fortune_advice['icon_url'] = $k;
                //转换tips
                foreach ($fortuneConfigs['guide_tips_' . $k] as $guide_k => $guide_v)
                {
                    if ($guide_v == $fortune_advice['tips'])
                    {
                        $fortune_advice['tips'] = $guide_k;
                        break;
                    }
                }
            }
        }
        return $fortune_advice;
    }

    /**
     * 把运势指南 cache转换为原始数据
     * @param $fortune_advice
     * @return array
     */
    private function transAdivceFromCacheToOriginal($fortune_advice)
    {
        //转换词条
        if (strlen($fortune_advice['tips']) < 4)
        {
            $fortune_advice['tips'] = config('fortune.guide_tips_' . $fortune_advice['icon_url'])[$fortune_advice['tips']];
        }
        //转换图标
        if (substr($fortune_advice['icon_url'], strlen($fortune_advice['icon_url']) - 3, 3) != 'png')
        {
            $fortune_advice['icon_url'] = $this->guide_icon_urls[$fortune_advice['icon_url']];
        }
        return $fortune_advice;
    }

    /**
     * 检查日运势解锁状态
     * @param int $uid
     * @param int $rid 当前查看档案
     * @param int $time 当前查看日期 时间戳
     * @param int $vipExpireTime 会员过期时间
     * @return array
     * @throws \Exception
     */
    public static function CheckFortuneSevenUnlockStatus(int $uid, int $rid, int $time, int $vipExpireTime = 0): array
    {
        $time1 = strtotime('-3day', $time);
        $time2 = strtotime('-2day', $time);
        $time3 = strtotime('-1day', $time);
        $time4 = strtotime('+1day', $time);
        $time5 = strtotime('+2day', $time);
        $time6 = strtotime('+3day', $time);
        $times = [
            1 => $time1,
            2 => $time2,
            3 => $time3,
            4 => $time,
            5 => $time4,
            6 => $time5,
            7 => $time6,
        ];
        $now_time = strtotime(date('Y-m-d'));
        //判单当前查看的时间饭后否包含今日
        if (in_array($now_time, $times))
        {
            $is_have_now_day = true;
        } else
        {
            $is_have_now_day = false;
        }

        //获取用户已解锁的所有时间
        $unlockData = self::getUnlockFortune($uid, $rid, 2);
        $vipUnlockDate = self::getVipUnlockDayTimeList($vipExpireTime);
        //获取日运七日解锁范围和日记标识时间范围
        $unlockData['note_time'] = array_values(array_intersect($times, $unlockData['note_time']));
        $unlockData['unlock_fortune'] = array_values(array_intersect($times, $unlockData['unlock_fortune']));
        $unlockData['vip_unlock'] = array_values(array_intersect($times, $vipUnlockDate));

        return self::CheckTimeUnlcokStatus($uid, $unlockData, $time, $is_have_now_day);
    }

    /**
     * 2.10.5 版本
     * 获取 vip 权益 日运 自动解锁的时间
     * @param int $vipExpireTime
     * @return array
     */
    public static function getVipUnlockDayTimeList(int $vipExpireTime = 0)
    {
        if ($vipExpireTime)
        {
            $now_time = strtotime(date('Y-m-d'));
            $times = [];
            for ($i = -30; $i < 30; $i++)
            {
                $t = $now_time + ($i * 86400);
                if ($t < $vipExpireTime)
                {
                    $times[] = $t;
                }
            }
            return $times;
        }
        return [];
    }

    /**
     * 检查日运势解锁状态
     * @param int $uid
     * @param int $rid 当前查看档案
     * @param int $time 当前查看日期
     * @return array
     * @throws \Exception
     */
    public static function CheckFortuneMonthUnlockStatus(int $uid, int $rid, int $time, int $vipExpireTime = 0): array
    {
        //获取用户一月解锁状态
        //获取当前月份 总共有多少天
        $month = month_days($time);
        $now_time = strtotime(date('Y-m'));

        //判单当前查看的时间饭后否包含是本月
        if (in_array($now_time, $month))
        {
            $is_have_now_month = true;
        } else
        {
            $is_have_now_month = false;
        }

        //获取档案所有解锁时间范围
        $unlockData = self::getUnlockFortune($uid, $rid, 2);
        $vipUnlockDate = self::getVipUnlockDayTimeList($vipExpireTime);
        //获取日运当月解锁范围和日记标识时间范围
        $unlockData['note_time'] = array_values(array_intersect($month, $unlockData['note_time']));
        $unlockData['unlock_fortune'] = array_values(array_intersect($month, $unlockData['unlock_fortune']));
        $unlockData['vip_unlock'] = array_values(array_intersect($month, $vipUnlockDate));

        //获取当前时间解锁状态
        return self::CheckTimeUnlcokStatus($uid, $unlockData, $time, $is_have_now_month);
    }

    /**
     * 检测用户当前时间解锁信息
     * @param $uid
     * @param $unlockData
     * @param $time
     * @param $now_day //true=》返回当日，false=》不反悔当日
     * @return mixed
     * @throws \Exception
     */
    public static function CheckTimeUnlcokStatus($uid, $unlockData, $time, $now_day)
    {
        $app_type = request()->header('app-type');
        //默认无日记
        $unlockData['note_status'] = 0;
        //默认日记标识为空
        $unlockData['time'] = [];
        //默认解锁时间为空
        $unlockData['fortune'] = [];
        switch (true)
        {
            case $time == strtotime(date('Y-m-d'))://当天
            case $time >= self::$fortune_unlock_time[0] && $time <= self::$fortune_unlock_time[1]://永久免费解锁
            case in_array($time, $unlockData['unlock_fortune'])://用户购买或赠送
            case in_array($time, $unlockData['note_time'])://用户日记
            case isset($unlockData['vip_unlock']) && in_array($time, $unlockData['vip_unlock']): // VIP解锁
                $unlockData['is_unlock'] = true;
                break;
            default: //默认当前未解锁
                $unlockData['is_unlock'] = false;
                break;
        }
        //判断用户当前是否有日记
        if (in_array($time, $unlockData['note_time']))
        {
            $unlockData['note_status'] = 1;
        }
        if ($app_type == 'ios')
        {
            $unlockData['time'] = array_map(function ($timeValue)
            {
                return date('d', $timeValue);
            }, $unlockData['note_time']);    // 将解锁时间的数据从日期格式转换成时间戳
            $unlockData['fortune'] = array_map(function ($timeValue)
            {
                return date('d', $timeValue);
            }, $unlockData['unlock_fortune']);
            $unlockData['vip_time'] = array_map(function ($timeValue)
            {
                return date('d', $timeValue);
            }, $unlockData['vip_unlock']);
            if ($now_day === true)
            {
                $unlockData['fortune'][] = date('d');
            }
        } else
        {
            $unlockData['time'] = array_map(function ($timeValue)
            {
                return date('j', $timeValue);
            }, $unlockData['note_time']);    // 将解锁时间的数据从日期格式转换成时间戳
            $unlockData['fortune'] = array_map(function ($timeValue)
            {
                return date('j', $timeValue);
            }, $unlockData['unlock_fortune']);
            $unlockData['vip_time'] = array_map(function ($timeValue)
            {
                return date('j', $timeValue);
            }, $unlockData['vip_unlock']);
            if ($now_day === true)
            {
                $unlockData['fortune'][] = date('j');
            }
        }
        //获取用户自己的档案
        $unlockData['selfId'] = (new Recode())->getRecodeLists($uid, 1);
        return $unlockData;
    }

    /**
     * 获取档案所有已解锁运势时间范围
     * @param int $uid
     * @param int $rid 当前查看档案
     * @param int $order_type 2=>日    3=>月    4=>年  12=>月运精简版
     * @return array
     * @throws \Exception 日运有前导零，月运无前导零
     */
    public static function getUnlockFortune(int $uid, int $rid, int $order_type): array
    {
        if ($order_type == 12)
        {
            $fortune_type = 3;
        } else
        {
            $fortune_type = $order_type;
        }
        //月运和年运需要区分计算状态
        $OrdersCacheModel = new Orders();
        $AwaradCacheModel = new AwardUser();
        $noteTime = [];//运势笔记时间范围
        //获取订单数据
        $orders = $OrdersCacheModel->PrepaidUnpaidOrder($uid, $rid, $order_type, 1);
        $fortune = array_column($orders, 'fortune_data');
        $unlockTime = [];// 解锁时间范围
        $computingTime = [];//计算中时间
        $completedTime = [];//已完成时间

        foreach ($orders as $order)
        {
            $ostatus = (int)$order['status'];
            $ofid = (int)$order['fid'];
            foreach ($fortune as $f)
            {
                $f = $f ? current($f) : [];
                $fid = (int)$f['id'];
                $fortuneOrderTime = prDates(['start' => $f['start_time'], 'end' => $f['end_time'], 'type' => $fortune_type - 1]); //1=>日 2=>月 3=>年
                switch (true)
                {
                    case $fortune_type === 3:
                        $fortuneOrderTime = array_map(function ($timeValue)
                        {
                            return $timeValue . '-1';
                        }, $fortuneOrderTime);
                        break;
                    case $fortune_type === 4:
                        $fortuneOrderTime = array_map(function ($timeValue)
                        {
                            return $timeValue . '-1-1';
                        }, $fortuneOrderTime);
                        break;
                }
                //月年有计算
                if (in_array($fortune_type, [2, 3, 4], true))
                {
                    if ($ostatus === 1 && $ofid === $fid)
                    {
                        $unlockTime[] = $computingTime[] = $fortuneOrderTime; //1=>日 2=>月 3=>年
                        break;
                    }
                    if ($ostatus === 4 && $ofid === $fid)
                    {
                        $unlockTime[] = $completedTime[] = $fortuneOrderTime; //1=>日 2=>月 3=>年
                        break;
                    }
                }
            }
        }

        //获取赠送数据
        $awards = $AwaradCacheModel->getUserAwardFromCache($uid, $fortune_type - 1, $rid);
        $gids = array_values(array_unique(array_column($awards, 'gid'))); // 获取所有赠送的运势商品ID
        $goods = (new Goods())->batchGetInfoByIds($gids);   // 通过商品ID批量获取运势商品信息
        foreach ($awards as $awardItem)
        {
            if (empty($awardItem['extend']) || !isset($goods[$awardItem['gid']])) continue;
            $extend = json_decode($awardItem['extend'], true);
            $startTime = date('Y-m-d', $extend['award_time']);  // 解锁开始时间
            $endTime = date('Y-m-d', strtotime($goods[$awardItem['gid']]['expire_time'], $extend['award_time']) - 86400); // 解锁结束时间
            // 将赠送时间写入解锁范围数据内
            $fortuneTime = prDates(['start' => $startTime, 'end' => $endTime, 'type' => $fortune_type - 1]); //1=>日 2=>月 3=>年
            switch (true)
            {
                case $fortune_type == 3:
                    $FortuneTime = array_map(function ($timeValue)
                    {
                        return $timeValue . '-1';
                    }, $fortuneTime);
                    break;
                case $fortune_type == 4:
                    $FortuneTime = array_map(function ($timeValue)
                    {
                        return $timeValue . '-1-1';
                    }, $fortuneTime);
                    break;
                default :
                    $FortuneTime = $fortuneTime;
                    break;
            }
            //月年有计算
            if (in_array($fortune_type, [3, 4]))
            {
                if ($awardItem['status'] == 0)
                {
                    $computingTime[] = $FortuneTime; //1=>日 2=>月 3=>年
                }
                if ($awardItem['status'] == 1)
                {
                    $completedTime[] = $FortuneTime; //1=>日 2=>月 3=>年
                }
            }
            $unlockTime[] = $FortuneTime;
        }

        $computingTime = Util::array_many_one($computingTime);
        $computingTime = array_unique($computingTime);    // 去重
        $computingTime = array_map(function ($timeValue)
        {
            return strtotime($timeValue);
        }, $computingTime);    // 将解锁时间的数据从日期格式转换成时间戳

        $completedTime = Util::array_many_one($completedTime);
        $completedTime = array_unique($completedTime);    // 去重
        $completedTime = array_map(function ($timeValue)
        {
            return strtotime($timeValue);
        }, $completedTime);    // 将解锁时间的数据从日期格式转换成时间戳

        $unlockTime = Util::array_many_one($unlockTime);
        $unlockTime = array_unique($unlockTime);    // 去重
        $unlockTime = array_map(function ($timeValue)
        {
            return strtotime($timeValue);
        }, $unlockTime);    // 将解锁时间的数据从日期格式转换成时间戳

        // 获取指定时间内已解锁时间
        if ($fortune_type === 2)
        {   // 当获取日运解锁数据时
            $noteData = (new \App\Models\Api\FortuneNote())->getUserNote(['uid' => $uid]);
            if ($noteData)
            {
                $noteTime = array_column($noteData, 'time');
            }
        }
        return [
            'note_time' => $noteTime ? array_values($noteTime) : [],
            'unlock_fortune' => $unlockTime ? array_values($unlockTime) : [],
            'computing_fortune' => $computingTime ? array_values($computingTime) : [],
            'completed_fortune' => $completedTime ? array_values($completedTime) : [],
        ];
    }
}
